<?php
/**
 * Model Catalog
 * This action helper will lazy load models for controller actions. Basically,
 * any model is available through this catalog at any time, but it isn't loaded
 * until it is requested.
 * 
 * @package     VisiCommerce
 * @subpackage  Action Helpers
 * @author      Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright   (c) 2011 Luke Visinoni <luke.visinoni@gmail.com>
 * @version     $Id$
 */
class Visi_Controller_Action_Helper_ModelCatalog extends Zend_Controller_Action_Helper_Abstract {

    protected $_path;
    
    protected $_models;
    
    public function init() {
    
        $this->_path = realpath(APPLICATION_PATH . '/models/DbTable');
    
    }
    
    public function direct($name) {
    
        if (empty($this->_path)) {
            $this->init();
        }
        $name = $this->nameToClass($name);
        if (!class_exists($name)) {
            $file = $this->_path . '/' . $name . '.php';
            if (file_exists($file)) {
                require_once $file;
            } else {
                // throw new Visi_Db_Model_Exception_NotFound("Model $name was not found in $this->_path.");
            }
        }
        if (!isset($this->_models[$name])) {
            $this->_models[$name] = new $name;
        }
        return $this->_models[$name];
    
    }
    
    public function nameToClass($name) {
    
        $array = explode('_', $name);
        $array = array_map('strtolower', $array);
        $array = array_map('ucfirst', $array);
        return 'DbTable_' . implode('', $array);
    
    }

}